
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;


public class GenStringBuilder {
	
	private static final String TEMPLATE_DIR= "C:/WorkDev/Eclipse3.3.2/workspace/Spark/web/WEB-INF/templates";
	private static final String NAME = "checkBox";
	
	@SuppressWarnings("unchecked")
	private void genFile(String name) throws IOException{
		StringBuilder sb = new StringBuilder();
		sb.append("Map map = context.getMap();\r");
//		sb.append("map.putAll(context.getModel());\r");
		sb.append("StringBuilder sb = new StringBuilder();\r");
		File file = new File(TEMPLATE_DIR, name + ".ftl");
		List ls = FileUtils.readLines(file, "UTF-8");
		for(int i=0;i<ls.size();i++) {
        	String line = ls.get(i).toString();
        	sb.append(process(line));
		}
		sb.append("return sb.toString();\r");
		System.out.println(sb.toString());
	}
	
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws IOException {
		GenStringBuilder gsb = new GenStringBuilder();
		gsb.genFile(NAME);
//		String str = "你好啊 ${asdf}，欢迎光临?default('')}";
//		str = str.replaceAll("\\?default", "");
//		System.out.println(str.replaceAll("\\(\\'\\'\\)", ""));
	}
	
	public String process(String line) {
		StringBuilder sb = new StringBuilder();
		sb.append("sb.append(");
		line = line.replaceAll("\"", "\\\\\"");
		//System.out.println(line);
		if(line.indexOf("${") != -1 ) {
			boolean st = line.startsWith("${");
			boolean ed = line.endsWith("}");
			if(!st)sb.append("\"");
			if(st){
				line = line.replaceAll("\\$\\{", "get(map,\"");
			}else{
				line = line.replaceAll("\\$\\{", "\").append(get(map,\"");
			}
			if(ed){
				line = line.replaceAll("\\?default\\(\\'\\'\\)\\}", "\")");
				line = line.replaceAll("\\!\\}", "\")");
				line = line.replaceAll("\\}", "\")");
			}else{
				line = line.replaceAll("\\?default\\(\\'\\'\\)\\}", "\")).append(\"");
				line = line.replaceAll("\\!\\}", "\")).append(\"");
				line = line.replaceAll("\\}", "\")).append(\"");
			}
			sb.append(line);
			if(!ed)sb.append("\"");
			
		}else{
			sb.append("\"");
			sb.append(line);
			sb.append("\"");
		}
		sb.append(");\r");
		return  sb.toString();
	} 
	
	@SuppressWarnings("unchecked")
	public String get(Map map ,String key){
		return "";
	}
	
	@SuppressWarnings("unchecked")
	public String test(Map map){
		StringBuilder sb = new StringBuilder();
		return sb.toString();
	}
}
